/*
 * 前端工具库
 */
(function(){ 
	var Utils = {};
	var config = require('./config.js');
	var viewport = $('.viewport');
	//	判断是否为mock数据
	var isMock = viewport.data('mock') || 0;
	//	默认请求路径
	var baseUrl = viewport.data('url');
	//	设置当前页面title值
	$('title').text($('.body-title').data('title'));
	var webview_count = {};
	Utils.formatTime = function(date){
		var res = {};
		var _date = date;
		var day = _date.split(' ')[0].split('-'),
			time = _date.split(' ')[1].split(':');
		return res = {
			year: day[0],
			month: day[1],
			day: day[2],
			hour: time[0],
			minute: time[1],
			second: time[2]
		}

	}
	/**
	 * 获取数据
	 * @param  {String}   function name  app定义方法名
	 * @param  {String}   url  请求地址
	 * @param  {Object || String}   data 请求携带参数
	 * @param  {Function} cb   回调
	 * @param  {String}   type 请求方法类型
	 * @return {Boolean}        
	 */
	
	Utils.getData = function(func,url,data,cb,type){
		var _type = type || 'POST',
			_url = baseUrl;
		if(isMock){
			_url += config.online[url];
			$.ajax({
				url: _url,
				data: data,
				type: 'POST',
				dataType: 'json',
				contentType: "application/x-www-form-urlencoded",
				headers: {'Authorization':'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEwLCJpc3MiOiJodHRwOi8vbG9jYWwuaHVveWkueGlhb3h4eC5jb20vYXBpL2F1dGgvd2VpeGluTG9naW4iLCJpYXQiOjE1MDQ3ODA0NzksImV4cCI6MTUwNzM3MjQ3OSwibmJmIjoxNTA0NzgwNDc5LCJqdGkiOiJTZXBxT25FSTQ1MXpSNHA0In0.Hzz_2ioVCK9dC7s7Jr3x5DdDKR7nNpIuV5LhPxp9wSE'},
				crossDomain: true,
				success: function(res){
					if(!res) {
						console.log('no response!')
						return;
					}
					try{
						$.isPlainObject(res)
					} catch (e){
						console.error('数据解析错误')
						return;
					}
					cb && cb(res);
				},
				error: function(res){
					console.error(res);
				}
			}) 
		} else {
			_url += config.online[url];
			connectWebViewJavascriptBridge(function(bridge) {
				if(bridge.init){
					if(!webview_count['first']) {
						webview_count['first'] = 'first';
						bridge.init(function(message, responseCallback) {
			                console.log('JS got a message', message);
			                var data = {
			                    'Javascript Responds': '测试中文!'
			                };
			                console.log('JS responding with', data);
			                responseCallback(data);
			            });
					}
				}
				
				//	getData方法
				if(func === 'getData'){
					bridge.callHandler('getData',{url: _url, data: data}, function responseCallback(responseData) {
						console.log(responseData)
						/*if(!responseData) {
							console.log('no response!')
							return;
						}
						if($.isPlainObject(responseData)) {
							var _res = JSON.parse(responseData);
						}*/
						cb && cb(responseData);
					})
				}
			})
		}
		function connectWebViewJavascriptBridge(callback) {
            if (window.WebViewJavascriptBridge) {
                callback(WebViewJavascriptBridge)
            } else {
            	document.addEventListener(
	                'WebViewJavascriptBridgeReady'
	                , function() {
	                    callback(WebViewJavascriptBridge)
	                },
	                false
	            );
            }
 
            if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }

	        window.WVJBCallbacks = [callback];
	        var WVJBIframe = document.createElement('iframe');
	        WVJBIframe.style.display = 'none';
	        WVJBIframe.src = 'https://__bridge_loaded__';
	        document.documentElement.appendChild(WVJBIframe);
	        setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
            
        }
	}
	module.exports = Utils;
})()